import express from 'express'
import { authenticateToken } from '../middleware/auth.js'
import db, { generateId } from '../db/database.js'
import { USDT_PRECISION } from '../config.js'

const router = express.Router()

// 统一转换余额：如果数据库存储的是原始值（>=1），需要除以 USDT_PRECISION
// 如果数据库存储的是转换后的值（<1），则不再转换
function normalizeBalance(value, currency = 'USDT') {
  if (value === null || value === undefined) return 0
  if (typeof value !== 'number') {
    value = parseFloat(value)
    if (isNaN(value)) return 0
  }
  
  if (currency === 'USDT') {
    // 判断：如果值大于等于1，很可能是原始值，需要转换；否则可能是已经转换的值
    if (value >= 1) {
      return value / USDT_PRECISION
    }
    // 如果值小于1，说明已经是转换后的值，直接返回
    return value
  }
  
  return value
}

// 将标准值转换回数据库存储格式
// 如果原始值是原始格式（>=1），需要将标准值乘回原始格式
// 如果原始值是标准格式（<1），直接返回标准值
function denormalizeBalance(normalizedValue, originalValue, currency = 'USDT') {
  if (normalizedValue === null || normalizedValue === undefined) return 0
  if (typeof normalizedValue !== 'number') {
    normalizedValue = parseFloat(normalizedValue)
    if (isNaN(normalizedValue)) return 0
  }
  
  if (currency === 'USDT') {
    // 判断原始值的格式
    const original = originalValue !== null && originalValue !== undefined 
      ? (typeof originalValue === 'number' ? originalValue : parseFloat(originalValue) || 0)
      : 0
    
    // 如果原始值 >= 1，说明数据库存储的是原始格式，需要乘回去
    if (original >= 1) {
      return normalizedValue * USDT_PRECISION
    }
    // 如果原始值 < 1，说明数据库存储的是标准格式，直接返回
    return normalizedValue
  }
  
  return normalizedValue
}

// 所有路由需要认证
router.use(authenticateToken)

// 发布C2C订单（买单或卖单）
router.post('/orders', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { type, currency = 'USDT', amount, price, minAmount = 0, maxAmount, paymentMethod, remark, expiresIn } = req.body

    // 参数验证
    if (!type || !['buy', 'sell'].includes(type)) {
      return res.status(400).json({
        code: 400,
        message: '订单类型必须是 buy 或 sell',
        success: false
      })
    }

    if (!amount || amount <= 0) {
      return res.status(400).json({
        code: 400,
        message: '订单金额必须大于0',
        success: false
      })
    }

    if (!price || price <= 0) {
      return res.status(400).json({
        code: 400,
        message: '价格必须大于0',
        success: false
      })
    }

    // 如果是卖单，检查余额
    if (type === 'sell') {
      const wallet = db.prepare('SELECT * FROM wallets WHERE user_id = ? AND currency = ?').get(userId, currency)
      if (!wallet) {
        return res.status(404).json({
          code: 404,
          message: '钱包不存在，请先创建钱包',
          success: false
        })
      }

      const dbBalance = normalizeBalance(wallet.balance || 0, currency)
      if (dbBalance < amount) {
        return res.status(400).json({
          code: 400,
          message: '余额不足',
          success: false
        })
      }

      // 冻结余额（从可用余额中扣除）
      const newBalance = dbBalance - amount
      // 将标准值转换回数据库存储格式
      const dbNewBalance = denormalizeBalance(newBalance, wallet.balance, currency)
      db.prepare('UPDATE wallets SET balance = ? WHERE id = ?').run(dbNewBalance, wallet.id)
    }

    // 生成订单ID
    const orderId = `C2C${Date.now()}${Math.random().toString(36).substr(2, 6).toUpperCase()}`
    const id = generateId()

    // 计算过期时间（默认24小时）
    const expiresAt = expiresIn 
      ? new Date(Date.now() + expiresIn * 60 * 1000).toISOString()
      : new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()

    // 创建订单
    db.prepare(`
      INSERT INTO c2c_orders (id, order_id, user_id, type, currency, amount, price, min_amount, max_amount, payment_method, status, remark, expires_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?)
    `).run(id, orderId, userId, type, currency, amount, price, minAmount, maxAmount || null, paymentMethod || null, remark || null, expiresAt)

    const order = db.prepare('SELECT * FROM c2c_orders WHERE id = ?').get(id)

    res.json({
      code: 200,
      message: '订单发布成功',
      success: true,
      data: {
        orderId: order.order_id,
        type: order.type,
        currency: order.currency,
        amount: order.amount,
        price: order.price,
        minAmount: order.min_amount,
        maxAmount: order.max_amount,
        paymentMethod: order.payment_method,
        status: order.status,
        remark: order.remark,
        createdAt: order.created_at,
        expiresAt: order.expires_at
      }
    })
  } catch (error) {
    next(error)
  }
})

// 获取订单列表
router.get('/orders', async (req, res, next) => {
  try {
    const { type, currency = 'USDT', status = 'active', page = 1, pageSize = 20 } = req.query

    let query = 'SELECT o.*, u.username FROM c2c_orders o JOIN users u ON o.user_id = u.id WHERE 1=1'
    const params = []

    if (type) {
      query += ' AND o.type = ?'
      params.push(type)
    }

    if (currency) {
      query += ' AND o.currency = ?'
      params.push(currency)
    }

    if (status) {
      query += ' AND o.status = ?'
      params.push(status)
    }

    // 过滤过期订单
    query += ' AND (o.expires_at IS NULL OR o.expires_at > datetime(\'now\'))'

    query += ' ORDER BY o.created_at DESC LIMIT ? OFFSET ?'
    params.push(parseInt(pageSize), (parseInt(page) - 1) * parseInt(pageSize))

    const orders = db.prepare(query).all(...params)

    // 获取总数
    let countQuery = 'SELECT COUNT(*) as total FROM c2c_orders WHERE 1=1'
    const countParams = []

    if (type) {
      countQuery += ' AND type = ?'
      countParams.push(type)
    }

    if (currency) {
      countQuery += ' AND currency = ?'
      countParams.push(currency)
    }

    if (status) {
      countQuery += ' AND status = ?'
      countParams.push(status)
    }

    countQuery += ' AND (expires_at IS NULL OR expires_at > datetime(\'now\'))'
    const total = db.prepare(countQuery).get(...countParams).total

    res.json({
      code: 200,
      message: '获取成功',
      success: true,
      data: {
        list: orders.map(order => ({
          orderId: order.order_id,
          type: order.type,
          currency: order.currency,
          amount: order.amount,
          price: order.price,
          minAmount: order.min_amount,
          maxAmount: order.max_amount,
          paymentMethod: order.payment_method,
          status: order.status,
          remark: order.remark,
          username: order.username,
          createdAt: order.created_at,
          expiresAt: order.expires_at
        })),
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    })
  } catch (error) {
    next(error)
  }
})

// 获取我的订单
router.get('/orders/my', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { status, type, page = 1, pageSize = 20 } = req.query

    let query = 'SELECT * FROM c2c_orders WHERE user_id = ?'
    const params = [userId]

    if (status) {
      query += ' AND status = ?'
      params.push(status)
    }

    if (type) {
      query += ' AND type = ?'
      params.push(type)
    }

    query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?'
    params.push(parseInt(pageSize), (parseInt(page) - 1) * parseInt(pageSize))

    const orders = db.prepare(query).all(...params)

    // 获取总数
    let countQuery = 'SELECT COUNT(*) as total FROM c2c_orders WHERE user_id = ?'
    const countParams = [userId]

    if (status) {
      countQuery += ' AND status = ?'
      countParams.push(status)
    }

    if (type) {
      countQuery += ' AND type = ?'
      countParams.push(type)
    }

    const total = db.prepare(countQuery).get(...countParams).total

    res.json({
      code: 200,
      message: '获取成功',
      success: true,
      data: {
        list: orders.map(order => ({
          orderId: order.order_id,
          type: order.type,
          currency: order.currency,
          amount: order.amount,
          price: order.price,
          minAmount: order.min_amount,
          maxAmount: order.max_amount,
          paymentMethod: order.payment_method,
          status: order.status,
          remark: order.remark,
          createdAt: order.created_at,
          expiresAt: order.expires_at
        })),
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    })
  } catch (error) {
    next(error)
  }
})

// 获取订单详情
router.get('/orders/:orderId', async (req, res, next) => {
  try {
    const { orderId } = req.params

    const order = db.prepare(`
      SELECT o.*, u.username 
      FROM c2c_orders o 
      JOIN users u ON o.user_id = u.id 
      WHERE o.order_id = ?
    `).get(orderId)

    if (!order) {
      return res.status(404).json({
        code: 404,
        message: '订单不存在',
        success: false
      })
    }

    res.json({
      code: 200,
      message: '获取成功',
      success: true,
      data: {
        orderId: order.order_id,
        type: order.type,
        currency: order.currency,
        amount: order.amount,
        price: order.price,
        minAmount: order.min_amount,
        maxAmount: order.max_amount,
        paymentMethod: order.payment_method,
        status: order.status,
        remark: order.remark,
        username: order.username,
        createdAt: order.created_at,
        expiresAt: order.expires_at
      }
    })
  } catch (error) {
    next(error)
  }
})

// 接受订单（创建交易）
router.post('/orders/:orderId/accept', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { orderId } = req.params
    const { amount } = req.body

    // 获取订单
    const order = db.prepare('SELECT * FROM c2c_orders WHERE order_id = ?').get(orderId)
    if (!order) {
      return res.status(404).json({
        code: 404,
        message: '订单不存在',
        success: false
      })
    }

    // 不能接受自己的订单
    if (order.user_id === userId) {
      return res.status(400).json({
        code: 400,
        message: '不能接受自己的订单',
        success: false
      })
    }

    // 订单必须是活跃状态
    if (order.status !== 'active') {
      return res.status(400).json({
        code: 400,
        message: '订单已不可用',
        success: false
      })
    }

    // 检查订单是否过期
    if (order.expires_at && new Date(order.expires_at) < new Date()) {
      return res.status(400).json({
        code: 400,
        message: '订单已过期',
        success: false
      })
    }

    // 确定交易金额
    const tradeAmount = amount || order.amount

    // 验证金额范围
    if (tradeAmount < (order.min_amount || 0)) {
      return res.status(400).json({
        code: 400,
        message: `交易金额不能小于 ${order.min_amount}`,
        success: false
      })
    }

    if (order.max_amount && tradeAmount > order.max_amount) {
      return res.status(400).json({
        code: 400,
        message: `交易金额不能大于 ${order.max_amount}`,
        success: false
      })
    }

    if (tradeAmount > order.amount) {
      return res.status(400).json({
        code: 400,
        message: `交易金额不能大于订单金额 ${order.amount}`,
        success: false
      })
    }

    // 计算总金额
    const totalAmount = tradeAmount * order.price

    // 如果是买单（order.type === 'buy'），接受者是卖家，需要检查卖家余额
    // 如果是卖单（order.type === 'sell'），接受者是买家，需要检查买家余额（法币余额，这里简化处理）
    if (order.type === 'buy') {
      // 买单：接受者是卖家，需要检查卖家是否有足够的币
      const sellerWallet = db.prepare('SELECT * FROM wallets WHERE user_id = ? AND currency = ?').get(userId, order.currency)
      if (!sellerWallet) {
        return res.status(404).json({
          code: 404,
          message: '钱包不存在，请先创建钱包',
          success: false
        })
      }

      const dbBalance = normalizeBalance(sellerWallet.balance || 0, order.currency)
      if (dbBalance < tradeAmount) {
        return res.status(400).json({
          code: 400,
          message: '余额不足',
          success: false
        })
      }

      // 冻结卖家余额
      const newBalance = dbBalance - tradeAmount
      // 将标准值转换回数据库存储格式
      const dbNewBalance = denormalizeBalance(newBalance, sellerWallet.balance, order.currency)
      db.prepare('UPDATE wallets SET balance = ? WHERE id = ?').run(dbNewBalance, sellerWallet.id)
    } else {
      // 卖单：接受者是买家，需要检查买家是否有足够的法币（这里简化，实际应该检查法币余额）
      // 暂时只检查币种余额作为示例
      const buyerWallet = db.prepare('SELECT * FROM wallets WHERE user_id = ? AND currency = ?').get(userId, order.currency)
      if (!buyerWallet) {
        return res.status(404).json({
          code: 404,
          message: '钱包不存在，请先创建钱包',
          success: false
        })
      }
    }

    // 生成交易ID
    const tradeId = `TRADE${Date.now()}${Math.random().toString(36).substr(2, 6).toUpperCase()}`
    const id = generateId()

    // 确定买卖双方
    const buyerId = order.type === 'buy' ? order.user_id : userId
    const sellerId = order.type === 'buy' ? userId : order.user_id

    // 创建交易
    db.prepare(`
      INSERT INTO c2c_trades (id, trade_id, order_id, buyer_id, seller_id, currency, amount, price, total_amount, status, payment_method)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)
    `).run(id, tradeId, order.id, buyerId, sellerId, order.currency, tradeAmount, order.price, totalAmount, order.payment_method)

    // 更新订单剩余金额
    const remainingAmount = order.amount - tradeAmount
    if (remainingAmount <= 0) {
      // 订单已完成
      db.prepare('UPDATE c2c_orders SET status = \'completed\', updated_at = datetime(\'now\') WHERE id = ?').run(order.id)
    } else {
      // 更新订单金额
      db.prepare('UPDATE c2c_orders SET amount = ?, updated_at = datetime(\'now\') WHERE id = ?').run(remainingAmount, order.id)
    }

    const trade = db.prepare('SELECT * FROM c2c_trades WHERE id = ?').get(id)

    res.json({
      code: 200,
      message: '交易创建成功',
      success: true,
      data: {
        tradeId: trade.trade_id,
        orderId: order.order_id,
        buyerId: trade.buyer_id,
        sellerId: trade.seller_id,
        currency: trade.currency,
        amount: trade.amount,
        price: trade.price,
        totalAmount: trade.total_amount,
        status: trade.status,
        paymentMethod: trade.payment_method,
        createdAt: trade.created_at
      }
    })
  } catch (error) {
    next(error)
  }
})

// 取消订单
router.post('/orders/:orderId/cancel', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { orderId } = req.params

    // 获取订单
    const order = db.prepare('SELECT * FROM c2c_orders WHERE order_id = ?').get(orderId)
    if (!order) {
      return res.status(404).json({
        code: 404,
        message: '订单不存在',
        success: false
      })
    }

    // 只能取消自己的订单
    if (order.user_id !== userId) {
      return res.status(403).json({
        code: 403,
        message: '无权取消此订单',
        success: false
      })
    }

    // 订单必须是活跃状态
    if (order.status !== 'active') {
      return res.status(400).json({
        code: 400,
        message: '订单已不可取消',
        success: false
      })
    }

    // 如果是卖单，需要解冻余额
    if (order.type === 'sell') {
      const wallet = db.prepare('SELECT * FROM wallets WHERE user_id = ? AND currency = ?').get(userId, order.currency)
      if (wallet) {
        const dbBalance = normalizeBalance(wallet.balance || 0, order.currency)
        const newBalance = dbBalance + order.amount
        // 将标准值转换回数据库存储格式
        const dbNewBalance = denormalizeBalance(newBalance, wallet.balance, order.currency)
        db.prepare('UPDATE wallets SET balance = ? WHERE id = ?').run(dbNewBalance, wallet.id)
      }
    }

    // 更新订单状态
    db.prepare('UPDATE c2c_orders SET status = \'cancelled\', updated_at = datetime(\'now\') WHERE id = ?').run(order.id)

    res.json({
      code: 200,
      message: '订单已取消',
      success: true
    })
  } catch (error) {
    next(error)
  }
})

// 获取交易列表
router.get('/trades', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { status, page = 1, pageSize = 20 } = req.query

    let query = `
      SELECT t.*, 
             buyer.username as buyer_username,
             seller.username as seller_username,
             o.type as order_type
      FROM c2c_trades t
      JOIN users buyer ON t.buyer_id = buyer.id
      JOIN users seller ON t.seller_id = seller.id
      JOIN c2c_orders o ON t.order_id = o.id
      WHERE (t.buyer_id = ? OR t.seller_id = ?)
    `
    const params = [userId, userId]

    if (status) {
      query += ' AND t.status = ?'
      params.push(status)
    }

    query += ' ORDER BY t.created_at DESC LIMIT ? OFFSET ?'
    params.push(parseInt(pageSize), (parseInt(page) - 1) * parseInt(pageSize))

    const trades = db.prepare(query).all(...params)

    // 获取总数
    let countQuery = 'SELECT COUNT(*) as total FROM c2c_trades WHERE (buyer_id = ? OR seller_id = ?)'
    const countParams = [userId, userId]

    if (status) {
      countQuery += ' AND status = ?'
      countParams.push(status)
    }

    const total = db.prepare(countQuery).get(...countParams).total

    res.json({
      code: 200,
      message: '获取成功',
      success: true,
      data: {
        list: trades.map(trade => ({
          tradeId: trade.trade_id,
          orderId: trade.order_id,
          orderType: trade.order_type,
          buyerId: trade.buyer_id,
          buyerUsername: trade.buyer_username,
          sellerId: trade.seller_id,
          sellerUsername: trade.seller_username,
          currency: trade.currency,
          amount: trade.amount,
          price: trade.price,
          totalAmount: trade.total_amount,
          status: trade.status,
          paymentMethod: trade.payment_method,
          paymentInfo: trade.payment_info,
          buyerRemark: trade.buyer_remark,
          sellerRemark: trade.seller_remark,
          createdAt: trade.created_at,
          paidAt: trade.paid_at,
          completedAt: trade.completed_at,
          isBuyer: trade.buyer_id === userId,
          isSeller: trade.seller_id === userId
        })),
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    })
  } catch (error) {
    next(error)
  }
})

// 获取交易详情
router.get('/trades/:tradeId', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { tradeId } = req.params

    const trade = db.prepare(`
      SELECT t.*, 
             buyer.username as buyer_username,
             seller.username as seller_username,
             o.type as order_type
      FROM c2c_trades t
      JOIN users buyer ON t.buyer_id = buyer.id
      JOIN users seller ON t.seller_id = seller.id
      JOIN c2c_orders o ON t.order_id = o.id
      WHERE t.trade_id = ?
    `).get(tradeId)

    if (!trade) {
      return res.status(404).json({
        code: 404,
        message: '交易不存在',
        success: false
      })
    }

    // 只能查看自己参与的交易
    if (trade.buyer_id !== userId && trade.seller_id !== userId) {
      return res.status(403).json({
        code: 403,
        message: '无权查看此交易',
        success: false
      })
    }

    res.json({
      code: 200,
      message: '获取成功',
      success: true,
      data: {
        tradeId: trade.trade_id,
        orderId: trade.order_id,
        orderType: trade.order_type,
        buyerId: trade.buyer_id,
        buyerUsername: trade.buyer_username,
        sellerId: trade.seller_id,
        sellerUsername: trade.seller_username,
        currency: trade.currency,
        amount: trade.amount,
        price: trade.price,
        totalAmount: trade.total_amount,
        status: trade.status,
        paymentMethod: trade.payment_method,
        paymentInfo: trade.payment_info,
        buyerRemark: trade.buyer_remark,
        sellerRemark: trade.seller_remark,
        createdAt: trade.created_at,
        paidAt: trade.paid_at,
        completedAt: trade.completed_at,
        isBuyer: trade.buyer_id === userId,
        isSeller: trade.seller_id === userId
      }
    })
  } catch (error) {
    next(error)
  }
})

// 确认付款（买家操作）
router.post('/trades/:tradeId/pay', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { tradeId } = req.params
    const { paymentInfo, remark } = req.body

    // 获取交易
    const trade = db.prepare('SELECT * FROM c2c_trades WHERE trade_id = ?').get(tradeId)
    if (!trade) {
      return res.status(404).json({
        code: 404,
        message: '交易不存在',
        success: false
      })
    }

    // 必须是买家
    if (trade.buyer_id !== userId) {
      return res.status(403).json({
        code: 403,
        message: '只有买家可以确认付款',
        success: false
      })
    }

    // 交易状态必须是pending
    if (trade.status !== 'pending') {
      return res.status(400).json({
        code: 400,
        message: '交易状态不正确',
        success: false
      })
    }

    // 更新交易状态
    db.prepare(`
      UPDATE c2c_trades 
      SET status = 'paid', 
          payment_info = ?,
          buyer_remark = ?,
          paid_at = datetime('now'),
          updated_at = datetime('now')
      WHERE id = ?
    `).run(paymentInfo || null, remark || null, trade.id)

    res.json({
      code: 200,
      message: '付款确认成功',
      success: true
    })
  } catch (error) {
    next(error)
  }
})

// 确认收款（卖家操作，完成交易）
router.post('/trades/:tradeId/complete', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { tradeId } = req.params
    const { remark } = req.body

    // 获取交易
    const trade = db.prepare('SELECT * FROM c2c_trades WHERE trade_id = ?').get(tradeId)
    if (!trade) {
      return res.status(404).json({
        code: 404,
        message: '交易不存在',
        success: false
      })
    }

    // 必须是卖家
    if (trade.seller_id !== userId) {
      return res.status(403).json({
        code: 403,
        message: '只有卖家可以确认收款',
        success: false
      })
    }

    // 交易状态必须是paid
    if (trade.status !== 'paid') {
      return res.status(400).json({
        code: 400,
        message: '交易状态不正确，请等待买家付款',
        success: false
      })
    }

    // 开始事务
    const transaction = db.transaction(() => {
      // 更新交易状态
      db.prepare(`
        UPDATE c2c_trades 
        SET status = 'completed',
            seller_remark = ?,
            completed_at = datetime('now'),
            updated_at = datetime('now')
        WHERE id = ?
      `).run(remark || null, trade.id)

      // 转账：买家获得币，卖家扣除币（币已经从冻结余额中扣除）
      // 买家获得币
      let buyerWallet = db.prepare('SELECT * FROM wallets WHERE user_id = ? AND currency = ?').get(trade.buyer_id, trade.currency)
      if (!buyerWallet) {
        // 如果买家没有钱包，需要创建（这里简化，实际应该调用钱包创建逻辑）
        throw new Error('买家钱包不存在')
      }

      const buyerBalance = normalizeBalance(buyerWallet.balance || 0, trade.currency)
      const newBuyerBalance = buyerBalance + trade.amount
      // 将标准值转换回数据库存储格式
      const dbNewBuyerBalance = denormalizeBalance(newBuyerBalance, buyerWallet.balance, trade.currency)
      db.prepare('UPDATE wallets SET balance = ?, updated_at = datetime(\'now\') WHERE id = ?').run(dbNewBuyerBalance, buyerWallet.id)

      // 卖家的余额已经在接受订单（买单）或发布订单（卖单）时冻结
      // 完成交易时，冻结的余额已经被扣除，不需要额外操作
      // 因为：
      // - 买单：卖家在接受订单时已经冻结余额（余额已减少）
      // - 卖单：卖家在发布订单时已经冻结余额（余额已减少）
      // 所以完成交易时，只需要给买家增加余额即可

      // 创建交易记录
      const txId = generateId()
      // 买家记录
      db.prepare(`
        INSERT INTO transactions (id, tx_id, user_id, type, currency, amount, from_address, to_address, status, memo)
        VALUES (?, ?, ?, 'c2c_receive', ?, ?, ?, ?, 'confirmed', ?)
      `).run(txId, txId, trade.buyer_id, trade.currency, trade.amount, 'C2C', 'C2C', `C2C交易获得 ${trade.amount} ${trade.currency}`)

      // 卖家记录
      const txId2 = generateId()
      db.prepare(`
        INSERT INTO transactions (id, tx_id, user_id, type, currency, amount, from_address, to_address, status, memo)
        VALUES (?, ?, ?, 'c2c_send', ?, ?, ?, ?, 'confirmed', ?)
      `).run(txId2, txId2, trade.seller_id, trade.currency, trade.amount, 'C2C', 'C2C', `C2C交易支出 ${trade.amount} ${trade.currency}`)
    })

    transaction()

    res.json({
      code: 200,
      message: '交易完成',
      success: true
    })
  } catch (error) {
    next(error)
  }
})

// 取消交易
router.post('/trades/:tradeId/cancel', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { tradeId } = req.params

    // 获取交易
    const trade = db.prepare('SELECT * FROM c2c_trades WHERE trade_id = ?').get(tradeId)
    if (!trade) {
      return res.status(404).json({
        code: 404,
        message: '交易不存在',
        success: false
      })
    }

    // 必须是交易参与方
    if (trade.buyer_id !== userId && trade.seller_id !== userId) {
      return res.status(403).json({
        code: 403,
        message: '无权取消此交易',
        success: false
      })
    }

    // 交易状态必须是pending
    if (trade.status !== 'pending') {
      return res.status(400).json({
        code: 400,
        message: '只能取消待付款的交易',
        success: false
      })
    }

    // 开始事务
    const transaction = db.transaction(() => {
      // 更新交易状态
      db.prepare(`
        UPDATE c2c_trades 
        SET status = 'cancelled',
            updated_at = datetime('now')
        WHERE id = ?
      `).run(trade.id)

      // 解冻余额
      const order = db.prepare('SELECT * FROM c2c_orders WHERE id = ?').get(trade.order_id)
      if (order) {
        if (order.type === 'buy') {
          // 买单：解冻卖家的冻结余额
          const sellerWallet = db.prepare('SELECT * FROM wallets WHERE user_id = ? AND currency = ?').get(trade.seller_id, trade.currency)
          if (sellerWallet) {
            const sellerBalance = normalizeBalance(sellerWallet.balance || 0, trade.currency)
            const newSellerBalance = sellerBalance + trade.amount
            // 将标准值转换回数据库存储格式
            const dbNewSellerBalance = denormalizeBalance(newSellerBalance, sellerWallet.balance, trade.currency)
            db.prepare('UPDATE wallets SET balance = ? WHERE id = ?').run(dbNewSellerBalance, sellerWallet.id)
          }
        } else {
          // 卖单：解冻卖家的冻结余额（订单发布时冻结的）
          const sellerWallet = db.prepare('SELECT * FROM wallets WHERE user_id = ? AND currency = ?').get(trade.seller_id, trade.currency)
          if (sellerWallet) {
            const sellerBalance = normalizeBalance(sellerWallet.balance || 0, trade.currency)
            const newSellerBalance = sellerBalance + trade.amount
            // 将标准值转换回数据库存储格式
            const dbNewSellerBalance = denormalizeBalance(newSellerBalance, sellerWallet.balance, trade.currency)
            db.prepare('UPDATE wallets SET balance = ? WHERE id = ?').run(dbNewSellerBalance, sellerWallet.id)
          }
        }

        // 恢复订单金额
        const currentOrder = db.prepare('SELECT * FROM c2c_orders WHERE id = ?').get(trade.order_id)
        if (currentOrder && currentOrder.status === 'active') {
          const newOrderAmount = currentOrder.amount + trade.amount
          db.prepare('UPDATE c2c_orders SET amount = ?, updated_at = datetime(\'now\') WHERE id = ?').run(newOrderAmount, order.id)
        }
      }
    })

    transaction()

    res.json({
      code: 200,
      message: '交易已取消',
      success: true
    })
  } catch (error) {
    next(error)
  }
})

export default router

